package ngat.oss;

import ngat.message.OSS.*;
import ngat.util.logging.*;
import ngat.phase2.*; 
import ngat.instrument.*;
import ngat.phase2.nonpersist.*;

import java.text.*;
import java.util.*;
import java.io.*;

/**
 * Action: Checks a PEST installation's version information.
 * 
 * The (latest) clientSettings is compared to the client's PEST versions and
 * any for which the latest versions supercede PEST versions or for which
 * there is NO client version are noted in the upgrade properties. A change 
 * log is also created whcih can be displayed at the client.
 *
 * @author S.N.Fraser
 */
public class LOGIN_TOOLImpl extends TransactionImpl {

    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd 'T' HH:mm:ss");
   
    public static final SimpleDateFormat vdf = new SimpleDateFormat("yyyyMMddHH");
	
    /** Client's module versions.*/
    protected Properties versions;
    
    /** Stores the upgrades info.*/
    protected Properties upgrades;

    /** Stores current settings from OSS cinfig file.*/
    protected Properties  current;
    
    boolean      changed   = false;

    StringBuffer changes   = null;
    StringBuffer news      = null;
    StringBuffer errors    = null;
    String       module    = null;
    String       ugDate    = null; // Date of the latest version (Str).	
    String       oldDate   = null; // Date of client's version.  (Str).
    Date         dtUgDate  = null; // Date of latest version.    (Date).
    Date         dtOldDate = null; // Date of client's version.  (Date).
 
    /** Create a LOGINImpl from the request.*/
    public LOGIN_TOOLImpl(LOGIN_TOOL request) {
	super(request);
	this.versions =  request.getVersions();
    }
    
    /**
     *Checks version info. The upgrade info is stored in the global location
     * ServerContext.clientSettings as java.util.Properties with the following format:-
     *
     * &lt; <b>module</b>&gt; . name = name of module
     * &lt; <b>module</b>&gt; . date = formatted date (to the hour-of-day)
     * &lt; <b>module</b>&gt; . upgrade = location URL string
     *
     * e.g.
     * <ul>
     * <li>pest.software.name    = PEST Software Version 1.1.2
     * <li>pest.software.date    = 2001011207
     * <li>pest.software.upgrade = http://telescope.livjm.ac.uk/software/12/pest_1_1_2c.jar
     * </ul>
     * @return A list of upgrade info + change log.
     */
    public TRANSACTION_DONE exec() { 
	
	upgrades = new Properties();
	
	// Stores the upgrade log. These are built up as a table one row per upgrade.
	
	changes = new StringBuffer("<tr><td><b>Module</td><td>New Version</b></td></tr>");
	news    = new StringBuffer("<p><b>New Modules.</b>");
	errors  = new StringBuffer("<p><b>Errors during execution.</b>");
	
	// Check the contents of oss.clientSettings.
	
	current  = ServerContext.getClientSettings();
	
	Enumeration settings = current.propertyNames();
	while (settings.hasMoreElements()) {
	    module = (String)settings.nextElement();
	    System.err.println("Read: "+module);
	    if (module.indexOf(".date") != -1) {
		// Actual module name.
		module = module.substring(0, module.indexOf(".date"));
		System.err.println("Module: "+module);
		// The date and location of the upgrade.
		ugDate  = current.getProperty(module+".date");

		// See if the current.date is > version.date (i.e. newer).
		oldDate = versions.getProperty(module+".date");

		if (oldDate != null) {
		    // We already have a version of this module, check if it needs upgrading.
		    try {
			dtOldDate = vdf.parse(oldDate);
			try {
			    dtUgDate = vdf.parse(ugDate);
			    if (dtUgDate.after(dtOldDate)) {
				// This module does need upgrading.
				upgrade(false);
			    }
			} catch (ParseException px) {
			    // This should not happen - if it does its an OSS Error.
			    // log it for now.
			    errors.append("<li>Module: ("+module+") error reading upgrade info at server: "+px); 
			}
		    } catch (ParseException px) {
			// Log this parsing error.
			errors.append("<li>Module: ("+module+") error reading client version date "+px);
		    }			    		    
		} else {
		    // We  probably dont have the module at present so get it !
		    upgrade(true);		   
		}
		
	    } // Not a module date - ignore.
	}
	
	String log = new String("<html><h3>PEST Upgrade Log</h3>"+
				"<hr><p>"+"<table border = 1>"+changes+"</table>"+
				"<hr><p>"+"<ul>"+news+"</ul>"+
				"<hr><p>"+"<ul>"+errors+"</ul>"+
				"</html>");

	upgrades.setProperty("changed", (changed ? "true" : "false"));
	upgrades.setProperty("change.log", log);

	LOGIN_TOOL_DONE done = new LOGIN_TOOL_DONE(id);
	done.setSuccessful(true);
	done.setUpgrades(upgrades);	
	return done;
	
    }

    private void upgrade(boolean isNew) {

	String ugUrl  = current.getProperty(module+".upgrade"); // URL for the latest version.ugUrl 
	String ugDest = current.getProperty(module+".dest");    // Destination (clientside rel. installDir).
	System.err.println("--URL: "+ugUrl+" Dest: "+ugDest);
	if (ugUrl != null && ugDest != null) {
	    // Set the URL and dest for the upgrade.
	    upgrades.setProperty(module+".date",    ugDate);
	    upgrades.setProperty(module+".upgrade", ugUrl); 
	    upgrades.setProperty(module+".dest",    ugDest);
	    if (isNew) {
		news.append("<li>Require module ("+current.getProperty(module+".name")+" / "+module+")");
	    } else {			    
		changes.append("<tr>");
		changes.append("<td>"+current.getProperty(module+".name")+"</td>");
		changes.append("<td>"+sdf.format(dtUgDate)+"</td>");
		changes.append("</tr>");
	    }
	    changed = true;
	} else {
	    // We dont appear to know where it is !
	    if (ugUrl == null)
		errors.append("<li>Module: ("+module+") can't find upgrade URL.");
	    if (ugDest == null)
		errors.append("<li>Module: ("+module+") can't find upgrade Destination.");
	}
	
    } // (upgrade).

}

/** $Log: LOGIN_TOOLImpl.java,v $
/** Revision 1.1  2006/11/27 08:45:00  snf
/** Initial revision
/**
/** Revision 1.1  2006/11/27 08:37:05  snf
/** Initial revision
/** */
